let myAudio = uni.createInnerAudioContext();
//格式化播放时间为00：00
let formatDuration = (seconds) => {
	seconds = Math.round(seconds) //首先去掉小数
	let hour = Math.floor(seconds / 3600) >= 10 ? Math.floor(seconds / 3600) : '0' + Math.floor(seconds /
		3600);
	seconds -= 3600 * hour;
	let min = Math.floor(seconds / 60) >= 10 ? Math.floor(seconds / 60) : '0' + Math.floor(seconds / 60);
	seconds -= 60 * min;
	let sec = seconds >= 10 ? Math.round(seconds) : '0' + Math.round(seconds);
	if (hour == '00') {
		return min + ':' + sec
	}
	return hour + ':' + min + ':' + sec;
}

//Vuex.Store 构造器选项  :VUE3
const player = {
	namespaced: true,
	state: { //存放状态
		isShowPlayer: false,
		play_state: 'stop',
		play_list: [],
		indexOf: 0,
		duration: '00:00',
		currentTime: '00:00',
		sliderValue: 0,
		sliderMax: 100,
		bufferedTime: 0,
		repeat_state: 0, //是否循环播放|0循环，1单曲，2，随机
		volume: 0.7,
		volume_Mute: false
	},
	mutations: {
		init(state) {
			{
				console.log('开始监听')
				myAudio.onCanplay(function() {
					console.log('可以播放状态');
					state.duration = formatDuration(myAudio.duration)
					state.sliderMax = myAudio.duration
				})
				myAudio.onPlay(() => {
					this.commit('player/changeState', 'play')
					// state.play_state = 'play'
					console.log('开始播放')
				})
				myAudio.onPause(() => {
					this.commit('player/changeState', 'Pause')
					console.log('已暂停');
				})
				myAudio.onStop(() => {
					this.commit('player/changeState', 'stop')
					console.log('已停止');
				})
				//音频播放进度更新事件	
				myAudio.onTimeUpdate(() => {
					state.currentTime = formatDuration(myAudio.currentTime)
					state.sliderValue = myAudio.currentTime
					// console.log('已缓存:', myAudio.buffered)
					state.bufferedTime = myAudio.buffered
				})
				myAudio.onEnded((state) => {
					// if(state.repeat_state)
					// commit('changeState', 'stop')
					this.commit('player/playNext')
					console.log('播放自然停止');
				})
				myAudio.onWaiting((state) => {
					console.log('正在等待数据加载');
				})

			}
		},
		changeState(state, payload) {
			state.play_state = payload
			console.log('changeState:',payload)
			state.volume_Mute ? myAudio.volume = 0 : myAudio.volume = state.volume

		},
		changeIndex(state, newIndex) {
			console.log('changeIndex')
			state.indexOf = newIndex
		},
		changeRepeat(state) { //改变循环模式，有3种状态的三元表达式:expr ? 'res1' :(expr1 ? 'res2':'res3')
			state.repeat_state == 0 ? state.repeat_state = 1 : (state.repeat_state == 1 ? state.repeat_state =
				2 : state.repeat_state = 0)
		},
		sliderChange(state, e) {
			// console.log('value 发生变化：' + e.detail.value)
			// myAudio.currentTime = e.detail.value
			myAudio.seek(e.detail.value)
		},
		volumeChange(state, volume) {
			console.log(volume.detail.value)
			myAudio.volume = volume.detail.value
			state.volume = volume.detail.value
		},
		volumeMute(state) {
			state.volume_Mute = !state.volume_Mute
			state.volume_Mute ? myAudio.volume = 0 : myAudio.volume = state.volume
			console.log(state.volume)
		},
		//播放和暂停动作
		playOrPause(state) {
			if (state.play_list.length == 0) {
				uni.showToast({
					title: '列表为空,请先添加歌曲',
					icon: 'none'
				})
				return
			}
			if (state.play_state == "Pause") { //如果暂停状态
				myAudio.play();
				console.log('从暂停开始播放')
				return
			}
			if (state.play_state == "play") { //如果处于播放状态，重新播放

				console.log('暂停播放');
				myAudio.pause()
			}
			if (state.play_state == "stop") { //如果处于停止状态，重新播放
				console.log('停止状态播放')
				myAudio.src = state.play_list[0].music_src;
				myAudio.play();
				console.log('从停止状态开始播放')
				return
			}
		},
		// 添加音乐到播放列表
		addToList(state, payload) {
			const findRes = state.play_list.findIndex((e) => e.id == payload.id)
			console.log(findRes)
			this.commit('player/playerShowOrHidden')

			if (findRes == '-1') { //如果没有记录就添加
				state.play_list.push(payload)
			}
			if (payload.play == 1) {
				state.indexOf = state.play_list.findIndex((e) => e.id == payload.id)
			}
		},
		// 添加歌单音乐列表到播放列表
		addToList2(state, payload) {
			state.play_list=payload
			state.indexOf = 0
			this.commit('player/playerShowOrHidden')
		},
		checkListLength(state) {
			return 'checkListLength'
			try {
				throw new Error('Whoops!');
				return 'false'
			} catch (e) {
				console.log(e.name + ': ' + e.message);

			}
		},
		playList(state) {
			// this.commit('checkListLength')
			let listLength = state.play_list.length //获取列表长度
			if (listLength == 0) {
				uni.showToast({
					title: 'c请先添加歌曲',
					icon: 'error'
				})
				return
			}
			myAudio.src = state.play_list[state.indexOf].music_src;
			setTimeout(() => {
				myAudio.play();
			}, 800)

		},
		playNext(state) {
			let listLength = state.play_list.length //获取列表长度
			let randomIndex = Math.floor(Math.random() * (listLength)) //按列表长度取得随机索引

			if (state.indexOf == (listLength - 1)) { //判断如果当前是最后一首的情况，根据循环状态播放
				uni.showToast({
					title: '当前是最后一首'
				})
				if (state.repeat_state != 2) {
					state.indexOf = 0
				} else {
					state.indexOf = randomIndex
				}
				this.commit('player/playList')
				console.log('下一首1')
				return
			}

			if (state.repeat_state != 2) { //如果是循环播放或单曲播放，
				if (state.repeat_state == 1) {
					state.indexOf = state.indexOf
				}
				state.indexOf += 1
			} else { //如果是随机播放,生成随机的索引
				state.indexOf = randomIndex
			}
			this.commit('player/playList')
			console.log('下一首2')
		},
		playPrevious(state) {
			if (state.play_list.length == 0) {
				uni.showToast({
					title: '列表为空'
				})
				return
			}
			if (state.indexOf == 0) {
				uni.showToast({
					title: '没有上一首了'
				})
				if (state.repeat) { //如果开启了循环播放，那么从第一首开始播放
					state.indexOf = state.play_list.length - 1
				}
				return
			}
			state.indexOf -= 1
			console.log('上一首')
			this.commit('player/playList')
		},
		playerShowOrHidden(state) {
			state.isShowPlayer = true
			setTimeout(() => {
				state.isShowPlayer = false
			}, 6000)

		}

	},
	actions: {
		add({ //添加到列表后播放
			commit
		}, payload) {
			commit('addToList', payload)
		},
		play({ //播放列表的点击播放
			commit
		}, index) {
			console.log(index)
			commit('changeIndex', index)
			commit('playList')
		},
		playOne({ //页面列表的点击播放
			commit
		}, payload) {
			payload.play = 1
			commit('addToList', payload)
			commit('playList')
		},
		playList({ //歌单列表的播放
			commit
		}, payload) {
			payload.play = 1
			commit('addToList2', payload)
			commit('playList')
		},
		next({
			commit
		}) {
			console.log('next')
			commit('playNext')

		},
		previous({
			commit
		}) {
			commit('playPrevious')
		},
		repeatMod({
			commit
		}) {
			commit('changeRepeat')
		},
		volumeChange({
			commit
		}, volume) {
			commit('volumeChange', volume)
		}
	}
}


export default player
